package dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import beans.Package;
import beans.PackageInfo;

import utils.HibernateUtil;




/**
 * 包裹信息Dao
 * 
 * @author wjm
 * 
 */
public class PackageInfoDao {
	private SessionFactory sessionFactory;

	public PackageInfoDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	Transaction tr = null;

	// private PackageInfoDao dao = new PackageInfoDao();

	/**
	 * 保存新包裹信息
	 * 
	 * @param packageinfo
	 * @return
	 */
	public int save(PackageInfo packageinfo) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.save(packageinfo);
		tr.commit();
		session.close();
		return packageinfo.getId();
	}

	/**
	 * 保存多条包裹信息
	 * 
	 * @param packageinfo
	 * @return
	 */
	public Map<String, Integer> saveListOfPackageInfo(
			List<PackageInfo> packageinfo) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		for (int i = 0; i < packageinfo.size(); i++) {
			session.save(packageinfo.get(i));
		}
		tr.commit();
		session.close();
		map.put("sucess", 0);
		return map;
	}

	/**
	 * 获取值
	 * 
	 * @param num
	 * @param expCompany
	 * @return
	 */
	public int getNumOfPackageInfo(String num, String expCompany) {
		String hql = "select count(*) from PackageInfo p where p.packNum=? and p.companyName=?";
		Session session = sessionFactory.openSession();
		Query query = session.createQuery(hql);
		query.setParameter(0, num);
		query.setParameter(1, expCompany);
		return Integer.parseInt(query.uniqueResult().toString());
	}

	/**
	 * 获取包裹信息
	 * 
	 * @return
	 */
	public List<PackageInfo> getAllPackageInfo() {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(PackageInfo.class);
		List<PackageInfo> list = c.list();
		tr.commit();
		session.close();
		return list;
	}
	
	/**
	 * 根据快递单号返回相应包裹
	 * 
	 * @param parcelId
	 *            快递单号
	 * @return 快递包裹信息的集合
	 */

	public ArrayList<PackageInfo> parcelIdTomobileNum(String packNum) {

		Session session = sessionFactory.openSession();
		ArrayList<PackageInfo> packageInfos = null;
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(PackageInfo.class);
		c.add(Restrictions.eq("packNum", packNum));
		packageInfos = (ArrayList<PackageInfo>) c.list();

		tr.commit();
		session.close();
		return packageInfos;

	}

	public static void main(String[] args) {
		PackageInfoDao dao = new PackageInfoDao();
		System.out.println(dao.getAllPackageInfo().get(199).getCompanyName());
	}
}
